package com.wangyao.repeat;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.NavUtils;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends FragmentActivity implements
		ActionBar.TabListener {
	
	private static final String TAG = "ylyq";

	videoFragment video;
	vfileFragment vfile;
	
	public interface OnSelectedListener {
		public void onSelected(String file);
	}
	
	OnSelectedListener vSelectedListener= new OnSelectedListener() {
		public void onSelected(String file) {
			video.file = file;
			final ActionBar actionBar = getActionBar();
			actionBar.selectTab(actionBar.getTabAt(0));
		}
	};
	
	/**
	 * The serialization (saved instance state) Bundle key representing the
	 * current tab position.
	 */
	private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		video = new videoFragment();
		vfile  = new vfileFragment();
		
		vfile.setSelectedListener(vSelectedListener);

		// Set up the action bar to show tabs.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		actionBar.setDisplayShowCustomEnabled(false);
		actionBar.setDisplayShowHomeEnabled (false);
		actionBar.setDisplayShowTitleEnabled (false);

		// For each of the sections in the app, add a tab to the action bar.
		actionBar.addTab(actionBar.newTab().setText(R.string.title_section1)
				.setTabListener(this));
		actionBar.addTab(actionBar.newTab().setText(R.string.title_section2)
				.setTabListener(this));
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		// Restore the previously serialized current tab position.
		if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
			getActionBar().setSelectedNavigationItem(
					savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
		}
	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// Serialize the current tab position.
		outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getActionBar()
				.getSelectedNavigationIndex());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:

			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {

		if (tab.getPosition() == 0) {
			getSupportFragmentManager().beginTransaction().replace(R.id.container, video).commit();
		} else {
			getSupportFragmentManager().beginTransaction().replace(R.id.container, vfile).commit();
		}
	}
	

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}
	
	public static class videoFragment extends Fragment {
		/**
		 * The fragment argument representing the section number for this
		 * fragment.
		 */
		public static final String ARG_SECTION_NUMBER = "section_number";
		public String file = "";

		public videoFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
	                
	        return inflater.inflate(R.layout.video, container, false);
		}
		
	    @Override
	    public void onActivityCreated(Bundle savedInstanceState) {
	        super.onActivityCreated(savedInstanceState);

	        if (!file.equals("")) {
		        VideoView videoView = (VideoView) getActivity().findViewById(R.id.video);
				videoView.setVideoPath(file);
				videoView.setMediaController(new MediaController(getActivity()));
				videoView.requestFocus();
	        }
	    }
	}
	
	public static class vfileFragment extends ListFragment implements 
		LoaderManager.LoaderCallbacks<Cursor> {

		public vfileFragment() {
		}
		
	    // This is the Adapter being used to display the list's data.
	    SimpleCursorAdapter mAdapter;
	    OnSelectedListener mListener;

	    // These are the Contacts rows that we will retrieve.
	    static final String[] FILE_PROJECTION = new String[] {
            MediaStore.Video.Media.DATA, 
            MediaStore.Video.Media._ID, 
            MediaStore.Video.Media.DISPLAY_NAME,
	    };
		
	    @Override
	    public void onActivityCreated(Bundle savedInstanceState) {
	        super.onActivityCreated(savedInstanceState);
	        
	        // Create an empty adapter we will use to display the loaded data.
	        mAdapter = new SimpleCursorAdapter(getActivity(),
	                android.R.layout.simple_list_item_1, null,
	                new String[] { MediaStore.Video.Media.DISPLAY_NAME },
	                new int[] { android.R.id.text1 }, 0);
	        setListAdapter(mAdapter);
	        
	        getLoaderManager().initLoader(0, null, this);
	    }
	    
	    public void setSelectedListener(OnSelectedListener listener) {
	    	mListener = listener;
	    }

	    @Override
	    public void onListItemClick(ListView l, View v, int position, long id) {
	    	Cursor c = (Cursor) l.getItemAtPosition(position);
	    	String file = c.getString(0);
	    	mListener.onSelected(file);
	    }
	    
	    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
			return new CursorLoader(getActivity(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
					FILE_PROJECTION, null, null, null);
	    }

		public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
	        mAdapter.swapCursor(data);
	    }

	    public void onLoaderReset(Loader<Cursor> loader) {
	        mAdapter.swapCursor(null);
	    }
	}	
}
